/*
此页纯复制wysiwyg库
*/
import React, { Component } from 'react';
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css"
import "./css/rich_text_editor.less"


export default class RichTextEditor extends Component {
  state = {
    editorState: EditorState.createEmpty(), //构建一个初始化状态的编辑器+内容
  }

  onEditorStateChange = (editorState) => {
    this.setState({
      editorState,
    });
  };

  //得到转译好的富文本
  getRichText = () => {
    const { editorState } = this.state
    return draftToHtml(convertToRaw(editorState.getCurrentContent()))
  }
  //设置一个富文本
  setRichText = (html) => {
    //下面都是从文档里粘的，可以把带有标签的富文本转换为初始状态
    const contentBlock = htmlToDraft(html);
    if (contentBlock) {
      const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
      const editorState = EditorState.createWithContent(contentState);
      this.setState({
        editorState,
      })
    }
  }

  render() {
    const { editorState } = this.state;
    return (
      <div>
        <Editor
          editorState={editorState}
          wrapperClassName="demo-wrapper"  //控制整个富文本编辑器的样式
          editorClassName="demo-editor"    //控制编辑区的样式
          onEditorStateChange={this.onEditorStateChange}
        />
      </div>
    );
  }
}